package com.nbsaas.boot.controller.web;

import com.nbsaas.boot.rest.response.ListResponse;
import com.nbsaas.boot.rest.response.MapResponse;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.management.ThreadMXBean;
import java.lang.management.ThreadInfo;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class StateController {

    @PostMapping("/processList")
    public ListResponse<MapResponse> processList() {
        ListResponse<MapResponse> result = new ListResponse<>();
        List<MapResponse> processList = new ArrayList<>();
        
        try {
            // 获取所有进程信息
            List<ProcessHandle> allProcesses = ProcessHandle.allProcesses()
                    .collect(Collectors.toList());
            
            // 构建进程信息列表
            for (ProcessHandle process : allProcesses) {
                try {
                    ProcessHandle.Info info = process.info();
                    MapResponse processInfo = new MapResponse();
                    
                    // 进程基本信息
                    processInfo.put("pid", process.pid());
                    processInfo.put("alive", process.isAlive());
                    
                    // 进程详细信息
                    String command = info.command().orElse("Unknown");
                    processInfo.put("command", command);
                    
                    String[] arguments = info.arguments().orElse(new String[0]);
                    processInfo.put("arguments", String.join(" ", arguments));
                    
                    String user = info.user().orElse("Unknown");
                    processInfo.put("user", user);
                    
                    // 获取进程启动时间
                    long startTime = info.startInstant().orElse(null) != null ? 
                            info.startInstant().get().toEpochMilli() : 0;
                    processInfo.put("startTime", startTime);
                    
                    // 获取进程总CPU时间（如果可用）
                    long totalCpuTime = info.totalCpuDuration().orElse(null) != null ?
                            info.totalCpuDuration().get().toMillis() : 0;
                    processInfo.put("totalCpuTime", totalCpuTime);
                    
                    processList.add(processInfo);
                    
                } catch (Exception e) {
                    // 忽略无法获取信息的进程
                }
            }
            
            // 按CPU使用率排序（按总CPU时间排序）
            processList.sort((p1, p2) -> {
                Long cpu1 = (Long) p1.get("totalCpuTime");
                Long cpu2 = (Long) p2.get("totalCpuTime");
                return Long.compare(cpu2 != null ? cpu2 : 0, cpu1 != null ? cpu1 : 0); // 降序排列
            });
            
            // 限制返回数量，避免数据过多
            if (processList.size() > 50) {
                processList = processList.subList(0, 50);
            }
            
        } catch (Exception e) {
            // 如果出现异常，返回错误信息
            MapResponse errorInfo = new MapResponse();
            errorInfo.put("error", "获取进程信息失败: " + e.getMessage());
            processList.add(errorInfo);
        }
        
        result.setData(processList);
        return result;
    }
    
    @RequestMapping("/systemInfo")
    public MapResponse systemInfo() {
        MapResponse result = new MapResponse();
        
        try {
            OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean();
            MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
            
            // 系统基本信息
            result.put("osName", osBean.getName());
            result.put("osVersion", osBean.getVersion());
            result.put("osArch", osBean.getArch());
            result.put("availableProcessors", osBean.getAvailableProcessors());
            result.put("systemLoadAverage", osBean.getSystemLoadAverage());
            
            // 内存信息
            MemoryUsage heapMemoryUsage = memoryBean.getHeapMemoryUsage();
            MemoryUsage nonHeapMemoryUsage = memoryBean.getNonHeapMemoryUsage();
            
            result.put("heapMemoryUsed", heapMemoryUsage.getUsed());
            result.put("heapMemoryMax", heapMemoryUsage.getMax());
            result.put("heapMemoryCommitted", heapMemoryUsage.getCommitted());
            result.put("nonHeapMemoryUsed", nonHeapMemoryUsage.getUsed());
            result.put("nonHeapMemoryMax", nonHeapMemoryUsage.getMax());
            result.put("nonHeapMemoryCommitted", nonHeapMemoryUsage.getCommitted());
            
            // 线程信息
            ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
            result.put("threadCount", threadBean.getThreadCount());
            result.put("peakThreadCount", threadBean.getPeakThreadCount());
            result.put("totalStartedThreadCount", threadBean.getTotalStartedThreadCount());
            
            // 进程信息
            long processCount = ProcessHandle.allProcesses().count();
            result.put("processCount", processCount);
            
        } catch (Exception e) {
            result.put("error", "获取系统信息失败: " + e.getMessage());
        }
        
        return result;
    }
}
